#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using TVC.Layout;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;

#endregion

namespace TVC.Modules.Ref
{
    public partial class RUS : ModuleParent, IHostedApplication
    {

        int idAllowEditLanguage = 1;
        int idAddNew = 143;
        int idEdit = 144;
        int idDelete = 145;
        int idTransferIn = 146;
        int idTransferOut = 147;
        int idPrint = 148;

        GridLayout layout = null;
        string strAction = "";
        DTO.PODInfo PODInfo;
        private string Business;
        public RUS()
        {
            _strType = "RUS";
            InitializeComponent();
            PODInfo = (DTO.PODInfo)Session["USER"];
        }

        public void InitializeApplication()
        {

        }

        //public void AddNew()
        //{

        //}

        public void SetObject(object obj)
        {

        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew))
                objElements.Add(new HostedToolBarButton("Add New", "New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idAddNew))
                objElements.Add(new HostedToolBarButton("Copy", "Copy", new IconResourceHandle("Copy.png"), "O"));
            if (IsPermis(idEdit))
                objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A"));
            if (IsPermis(idDelete))
                objElements.Add(new HostedToolBarButton("Delete", "Delete", new IconResourceHandle("Delete.png"), "X"));
            if (IsPermis(idAddNew) && IsPermis(idEdit))
                objElements.Add(new HostedToolBarButton("Save", "Save", new IconResourceHandle("Save.png"), "S"));

            // objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            //if (IsPermis(idAddNew))
            //    objElements.Add(new HostedToolBarButton("Sun", "Insert To SunSystems", new IconResourceHandle("Add.png"), "TS"));

            //objElements.Add(new HostedToolBarSeperator());
            //if (IsPermis(idTransferIn))
            //    objElements.Add(new HostedToolBarButton("Transfer In", "Import", new IconResourceHandle("Down.png"), "TI"));
            //if (IsPermis(idTransferOut))
            //    objElements.Add(new HostedToolBarButton("Transfer Out", "Export", new IconResourceHandle("Up.png"), "TO"));
            //objElements.Add(new HostedToolBarSeperator());
            //if (IsPermis(idPrint))
            //    objElements.Add(new HostedToolBarButton("Print", new IconResourceHandle("Print.png"), "P"));
            objElements.Add(new HostedToolBarButton("Refresh", "Refresh", new IconResourceHandle("Refresh.png"), "R", false));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }
        protected override void SetupToolBar(string strAction)
        {
            ToolBar tbarLocal = GetTbarLocal();
            bool on = true, off = false;
            if (tbarLocal == null) return;

            switch (strAction)
            {
                case "C":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    break;
                case "A":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    break;
                case "S":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    break;

                case "O":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    break;
                case "V":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    break;
            }

        }
        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            try
            {
                sErr = "";
                strAction = (string)objButton.Tag;

                BUS.RuleProfileControl ctr = new BUS.RuleProfileControl(PODInfo.Business_ID);
                switch (strAction)
                {
                    case "K":
                        skip();
                        break;
                    case "C":
                        AddNew(txtCode);
                        break;
                    case "A":
                        editRecord(txtCode);
                        break;
                    case "S":
                        saveRecord(txtCode, false);
                        break;
                    case "O":
                        copy(txtCode);
                        break;
                    case "X":
                        delete(txtCode);

                        break;
                    case "TI":
                        //Forms.frmTransferIn frmTI = new Forms.frmTransferIn(_strType, GetMainForm());
                        //frmTI.ShowDialog();
                        break;
                    case "TO":
                        //DataTable dt = _dtb;
                        //dt.TableName = _strType;
                        //Forms.frmTransferOut frmTO = new Forms.frmTransferOut(_strType, dt, GetMainForm());
                        //frmTO.Show();
                        break;
                    case "R":
                        reloadList();
                        break;
                    case "P":
                        //DTO.OrganizationsInfo info = new DTO.OrganizationsInfo((DataRowView)dgvTVC_LOOKUP.CurrentRow.DataBoundItem);
                        //DataTable dt = DTO.OrganizationsInfo.ToDataTable();
                        //dt.Rows.Add(info.ToDataRow(dt));
                        //DataSet ds = new DataSet();
                        //ds.Tables.Add(dt);
                        //MainForm main = GetMainForm();
                        //if (main != null)
                        //    main.PrintDataSet(ds, _strType);

                        break;
                }
                _processStatus = strAction;
                if (sErr == "")
                    ThrowMsg("Command: " + _processStatus);
            }
            catch (Exception ex)
            {
                ThrowMsg(ex.Message + Environment.NewLine + ex.Source);
            }
        }

        protected override void refreshForm(string str)
        {
            txtCode.Text = "";
            txtDescription.Text = "";
            cboFrom.Text = "";
            chkSuspend.Checked = false;
            RefreshList("");
        }

        private void RefreshList(string Filter)
        {
            BUS.RuleSetControl ctr = new BUS.RuleSetControl(PODInfo.Business_ID);
            dgvlist.AutoGenerateColumns = false;
            dgvlist.DataSource = ctr.GetbyRuleSetCode(GetMainForm().SUNDB, Filter, ref sErr);
        }

        protected override ErrorStatus validateForm(ref string sErr)
        {
            sErr = "";
            string sWarn = "";
            ErrorStatus result = ErrorStatus.SUCCESS;
            sErr = ValidItem();

            if (sErr != "") result = ErrorStatus.ERROR;
            else if (sWarn != "") result = ErrorStatus.WARNING;

            sErr = string.Format("{0}{1}", sErr, sWarn);

            return result;
        }

        private string ValidItem()
        {
            sErr = "";
            if (txtCode.Text == "")
            {
                sErr = "Coud not save blank Code, Please check!";
            }
            if (txtDescription.Text == "")
            {
                sErr = "Coud not save blank Description, Please check!";
            }
            if (cboFrom.Text == "")
            {
                sErr = "Coud not save blank From, Please check!";
            }
            return sErr;
        }

        protected override bool checkExists()
        {
            BUS.RuleProfileControl ctr = new BUS.RuleProfileControl(PODInfo.Business_ID);
            return ctr.IsExist(GetMainForm().SUNDB, txtCode.Text);
        }

        protected override string addRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.RuleProfileControl ctr = new BUS.RuleProfileControl(PODInfo.Business_ID);
            DTO.RuleProfileInfo info = GetData();
            object trans = ctr.BeginTransaction(ref sErr);
            if (sErr == "") ctr.Add(GetMainForm().SUNDB, info, ref sErr);
            if (sErr == "") sErr = UpdateDetail(info.RULESET_CODE, trans);

            if (sErr == "") sErr = ctr.updateRuleResult(GetMainForm().SUNDB, info, dgvlist.DataSource as DataTable);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);

            return sErr;
        }

        protected override string updateRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.RuleProfileControl ctr = new BUS.RuleProfileControl(PODInfo.Business_ID);
            DTO.RuleProfileInfo info = GetData();
            object trans = ctr.BeginTransaction(ref sErr);

            if (sErr == "") sErr = ctr.Update(GetMainForm().SUNDB, info);
            if (sErr == "") sErr = UpdateDetail(info.RULESET_CODE, trans);
            if (sErr == "") sErr = ctr.updateRuleResult(GetMainForm().SUNDB, info, dgvlist.DataSource as DataTable);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }

        protected override string delRecord()
        {
            string sErr = "";
            BUS.RuleProfileControl ctr = new BUS.RuleProfileControl(PODInfo.Business_ID);
            BUS.RuleSetControl ctrRuset = new BUS.RuleSetControl(PODInfo.Business_ID);
            object trans = ctr.BeginTransaction(ref sErr);
            if (sErr == "") ctrRuset.SetTransaction(trans);

            if (sErr == "") sErr = ctrRuset.Delete(GetMainForm().SUNDB, 0, txtCode.Text);

            if (sErr == "") sErr = ctr.delResult(GetMainForm().SUNDB, txtCode.Text);

            if (sErr == "") sErr = ctr.Delete(GetMainForm().SUNDB, txtCode.Text);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }

        protected override void loadRecord(object o)
        {
            if (o is DataRowView)
            {
                DTO.RuleProfileInfo inf = new DTO.RuleProfileInfo((DataRowView)o);
                SetData(inf);
            }
        }

        protected override void enableForm(bool N)
        {
            foreach (Control x in tbdeatil.Controls)
            {
                if (x is TextBox || x is ComboBox || x is TVC.Modules.CustomControl.MultiColumnCombo)
                {
                    x.Enabled = N;
                }
            }
            cboFilter.Enabled = true;
            mcbFilter.Enabled = true;
        }

        private void RUS_Load(object sender, EventArgs e)
        {
            LoadCombo();
            LoadFilter();
            LoadColumCombo();
            refreshForm("");
            enableForm(false);
            dgvlist.AutoGenerateColumns = false;
        }
        private void LoadFilter()
        {
            BUS.RuleProfileControl ctrztable = new BUS.RuleProfileControl(PODInfo.Business_ID);
            DataTable dt = ctrztable.GetAll(GetMainForm().SUNDB, ref sErr);

            GridLayout layoutRule = new GridLayout(MainForm.ServerPath
                + "Resources\\Layout\\", MainForm.ServerPath + "Documents\\Layout\\"
                + GetMainForm().PODInfo.USER_ID + "\\", "RuleProfile");
            GetMainForm().InitMultiComboBox(mcbFilter, layoutRule, DTO.RuleProfileInfo.Field.RULESET_CODE.ToString(), DTO.RuleProfileInfo.Field.DESCRIPTN.ToString());
            bisRuleProfile.DataSource = dt;
            mcbFilter.Binding = bisRuleProfile;

            cboFilter.DisplayMember = "DisplayCBO";
            cboFilter.ValueMember = "RULESET_CODE";
            cboFilter.DataSource = ctrztable.GetAll(GetMainForm().SUNDB, ref sErr);
            
        }


        private void LoadCombo()
        {
            BUS.zTableFieldControl ctrztable = new BUS.zTableFieldControl();
            DataTable dt = ctrztable.GetRuleSet("Y", ref sErr);
            bisFrom.DataSource = dt;
            GridLayout layoutFrom = new GridLayout(MainForm.ServerPath
                + "Resources\\Layout\\", MainForm.ServerPath + "Documents\\Layout\\"
                + GetMainForm().PODInfo.USER_ID + "\\", "RuleSet");
            mcbFrom.Binding = bisFrom;
            GetMainForm().InitMultiComboBox(mcbFrom, layoutFrom, "TableName", "FormCaption");

            cboFrom.DataSource = ctrztable.GetRuleSet("Y", ref sErr);
            cboFrom.DisplayMember = "DisplayCBO";
            cboFrom.ValueMember = "TableName";
        }


        private void SetData(DTO.RuleProfileInfo info)
        {
            txtCode.Text = info.RULESET_CODE;
            txtDescription.Text = info.DESCRIPTN;
            cboFrom.SelectedValue = info.TVC_TB;
            LoadColumCombo();
            if (info.SUSPEND == 1)
                chkSuspend.Checked = true;
            else
                chkSuspend.Checked = false;
        }

        private string UpdateDetail(string RULESET_CODE, object trans = null)
        {
            string sErr = "";
            BUS.RuleSetControl ctr = new BUS.RuleSetControl(PODInfo.Business_ID);
            if (trans != null) ctr.SetTransaction(trans);

            sErr = ctr.Delete(GetMainForm().SUNDB, 0, RULESET_CODE);
            DTO.RuleSetInfo info;


            for (int i = 0; i < dgvlist.Rows.Count; i++)
            {
                if (sErr != "" || dgvlist.Rows[i].IsNewRow) break;
                info = new DTO.RuleSetInfo((DataRowView)dgvlist.Rows[i].DataBoundItem);
                info.RULESET_CODE = RULESET_CODE;
                info.AUTO_ID = i;
                sErr = ctr.InsertUpdate(GetMainForm().SUNDB, info);
            }

            return sErr;
        }

        private DTO.RuleProfileInfo GetData()
        {
            int Suspend = 0;
            if (chkSuspend.Checked)
                Suspend = 1;

            return new DTO.RuleProfileInfo(txtCode.Text.Trim().ToUpper(), txtDescription.Text.Trim(), cboFrom.SelectedValue.ToString(), Suspend);

        }


        private void LoadColumCombo()
        {
            if (cboFrom.SelectedValue != null)
            {
                BUS.zTableFieldControl ctr = new BUS.zTableFieldControl();
                DataTable Dt = ctr.GetRuleSet(cboFrom.SelectedValue.ToString(), "Y", ref sErr);
                Dt.Rows.Add(Dt.NewRow());
                colField.DataSource = Dt;
                colField.DisplayMember = "LabelCaption";
                colField.ValueMember = "FieldName";
            }
        }


        private void btnUp_Click(object sender, EventArgs e)
        {
            if (dgvlist.CurrentCell != null)
            {
                if (dgvlist.CurrentCell.RowIndex > 0 && !dgvlist.CurrentRow.IsNewRow)
                {
                    DataTable dt = dgvlist.DataSource as DataTable;
                    if (dt != null)
                    {
                        DataRow r = dt.NewRow();
                        r.ItemArray = dt.Rows[dgvlist.CurrentCell.RowIndex].ItemArray;
                        dt.Rows.RemoveAt(dgvlist.CurrentCell.RowIndex);
                        dt.Rows.InsertAt(r, dgvlist.CurrentCell.RowIndex - 1);                        
                    }
                }
            }
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if (dgvlist.CurrentCell != null)
            {
                if (dgvlist.CurrentCell.RowIndex < dgvlist.Rows.Count - 2)
                {
                    DataTable dt = dgvlist.DataSource as DataTable;
                    if (dt != null)
                    {
                        DataRow r = dt.NewRow();
                        r.ItemArray = dt.Rows[dgvlist.CurrentCell.RowIndex].ItemArray;
                        dt.Rows.InsertAt(r, dgvlist.CurrentCell.RowIndex + 2);
                        dt.Rows.RemoveAt(dgvlist.CurrentCell.RowIndex);
                    }
                }
            }

        }

        private void txtCode_Leave(object sender, EventArgs e)
        {
            txtCode.Text = txtCode.Text.ToUpper();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvlist.CurrentRow != null)
                dgvlist.Rows.Remove(dgvlist.CurrentRow);
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            DataTable dt = dgvlist.DataSource as DataTable;
            if (dgvlist.CurrentRow != null)
            {
                dt.Rows.Add(((DataRowView)dgvlist.CurrentRow.DataBoundItem).Row.ItemArray);

            }
        }



        private void cboFrom_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cboFrom.SelectedValue != null)
                LoadColumCombo();
            string Filter = "";
            if (cboFilter.SelectedValue != null)
                Filter = cboFilter.SelectedValue.ToString();
            BUS.RuleSetControl ctr = new BUS.RuleSetControl(PODInfo.Business_ID);
            dgvlist.AutoGenerateColumns = false;
            dgvlist.DataSource = ctr.GetbyRuleSetCode(GetMainForm().SUNDB, Filter, ref sErr);
        }


        private void cboFilter_SelectedValueChanged(object sender, EventArgs e)
        {
            string Filter = "";
            if (cboFilter.SelectedValue != null)
                Filter = cboFilter.SelectedValue.ToString();
            BUS.RuleSetControl ctr = new BUS.RuleSetControl(PODInfo.Business_ID);
            dgvlist.AutoGenerateColumns = false;
            dgvlist.DataSource = ctr.GetbyRuleSetCode(GetMainForm().SUNDB, Filter, ref sErr);

            BUS.RuleProfileControl ctrPro = new BUS.RuleProfileControl(PODInfo.Business_ID);
            SetData(ctrPro.Get(GetMainForm().SUNDB, Filter, ref sErr));
        }
        private void dgvlist_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void cboFrom_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboFrom.SelectedValue != null)
            {
                mcbFrom.Text = cboFrom.SelectedValue.ToString();
                //txtExclaimerName.Text = ((DataTable)cboCategory.DataSource).Rows[cboCategory.SelectedIndex]["NAME"].ToString().Trim();
            }
        }

        private void mcbFrom_ComboText_Changed(object sender, CustomControl.MultiColumnCombo.ComboChangedEventArgs e)
        {
            if (mcbFrom.RowData != null)
                cboFrom.SelectedValue = mcbFrom.RowData["TableName"].ToString().Trim();
        }

        private void cboFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboFilter.SelectedValue != null)
            {
                mcbFilter.Text = cboFilter.SelectedValue.ToString();
                //txtExclaimerName.Text = ((DataTable)cboCategory.DataSource).Rows[cboCategory.SelectedIndex]["NAME"].ToString().Trim();
            }
        }

        private void mcbFilter_ComboText_Changed(object sender, CustomControl.MultiColumnCombo.ComboChangedEventArgs e)
        {
            if (mcbFilter.RowData != null)
                cboFilter.SelectedValue = mcbFilter.RowData["RULESET_CODE"].ToString().Trim();
        }
    }
}